package com.AsyncDemo;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * 创建异步任务
 *
 * */
public class FutrueSubmitDemo {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        test1();
    }

    //Future  执行异步任务
    public static void test1() throws ExecutionException, InterruptedException {
        //单线程池
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        Future<Double> future = executorService.submit(()->{
            System.out.println(Thread.currentThread().getName()+" start,time->"+System.currentTimeMillis());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
            }
            if(false){
                throw new RuntimeException("test");
            }else{
                System.out.println(Thread.currentThread().getName()+" exit,time->"+System.currentTimeMillis());
                return 1.2;
            }
        });
        System.out.println(Thread.currentThread().getName()+" thread start,time->"+System.currentTimeMillis());
        //等待子任务执行完成,如果已完成则直接返回结果
        //如果执行任务异常，则get方法会把之前捕获的异常重新抛出
        System.out.println("run result->"+future.get());
        System.out.println(Thread.currentThread().getName()+" thread exit,time->"+System.currentTimeMillis());

        executorService.shutdown();
    }
}
